<template>
  <div class="fileField" v-if="itemdata.lCanOutput === '1'">
    <template v-if="itemdata.lMustInput === '0'">
      <div style="padding: 10px 0;">{{ itemdata.sTitle }}</div>
      <input type="hidden" v-model="itemdata.valuehidden" />
      <input type="hidden" v-model="itemdata.value" />
      <van-uploader :before-read="beforeRead" placeholder="请选择文件" v-model="itemdata.valuelist" :after-read="onFileHead"
        @delete="delFileHead" accept="*" multiple :name="itemdata.sField">
        <template #preview-cover="{ file, url }">
          <div class="preview-cover van-ellipsis" @click.stop="downloadByUrl(file.name)">
            <!-- {{ url }} -->
            <van-icon name="down" />
            下载文件
          </div>
        </template>
      </van-uploader>
    </template>

    <template v-if="itemdata.lMustInput === '1'">
      <div style="padding: 10px 0;"><span style="color:red">*</span> {{ itemdata.sTitle }}</div>
      <input type="hidden" v-model="itemdata.valuehidden" />
      <input type="hidden" v-model="itemdata.value" />
      <van-uploader :before-read="beforeRead" placeholder="请选择文件" v-model="itemdata.valuelist" :after-read="onFileHead"
        @delete="delFileHead" accept="*" multiple :name="itemdata.sField">
        <template #preview-cover="{ file }">
          <div class="preview-cover van-ellipsis">
            <van-icon name="down" />

            <!-- {{ file.name }} -->
          </div>
        </template>
      </van-uploader>
    </template>
  </div>
</template>
<script>
import download$ from 'dingtalk-jsapi/api/device/audio/download'
import { Toast } from 'vant'
import Vue from 'vue'
Vue.use(Toast)
export default {
  props: {
    jsondata: {
      type: Object,
      required: false
    },
    itemdata: {
      type: Object,
      required: false
    },
    ishead: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      required: false
    }
  },
  data(){
    return {
      fileList:[],
      oldNameStr:this.itemdata.value || "",
      newNameStr:this.itemdata.valuehidden || ""

    }
  },
  methods: {
    downloadByUrl(filename){

      const index = this.oldNameStr.split(";").indexOf(filename)
      const newname = this.newNameStr.split(";")[index]
 

      if(newname){
        const url =  window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "/");
        console.log("url",url)
        window.location.href= `${url}/userfile/default/attach/${newname}` 
      }

    },
    downloadByData(blob, filename) {
      
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
       
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    },
    beforeRead(file) {
      // if (file.type !== 'application/pdf') {
      //   Toast('请上传pdf格式文件')
      //   return false
      // }
      return true
    },
    onFileHead(file, detail) {
      // 上传
      let deviceFile = []
      let formData = new FormData()
      if (Array.isArray(file)) {
        deviceFile = file
      } else {
        deviceFile.push(file)
      }
      for (let i = 0; i < deviceFile.length; i++) {
        formData.append('file' + i, deviceFile[i].file, deviceFile[i].name)
      }
      const toast = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '等待上传中...请稍候'
      })
      this.axios({
        method: 'post',
        url: '/api/upload.filedo',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        toast.clear()

        if (res.data.flag === '0') {
          let fileInfo = res.data.fileInfo

          this.oldNameStr += fileInfo[0].oldname+";"
          this.newNameStr += fileInfo[0].newname+";"
         
         
          
          if (this.ishead) {
            for (let headIdx = 0; headIdx < this.jsondata.head.length; headIdx++) {
              let headData = this.jsondata.head[headIdx].groupvalue
              for (let i = 0; i < headData.length; i++) {
                if (headData[i].sField === detail.name) {
                  headData[i].valuehidden = fileInfo[0].newname + ';' + (headData[i].valuehidden && headData[i].valuehidden != null && headData[i].valuehidden != undefined && headData[i].valuehidden != 'undefined' ? headData[i].valuehidden : '')
                  headData[i].value = fileInfo[0].oldname + ';' + (headData[i].value && headData[i].value != null && headData[i].value != undefined && headData[i].value != 'undefined' ? headData[i].value : '')
                }
              }
            }
          } else {
            // 目前只处理单子表（第一个子表）
            for (let key in this.jsondata.bodydata) {
              let headData = this.jsondata.bodydata[key][this.index]
              for (let i = 0; i < headData.length; i++) {
                if (headData[i].sField === detail.name) {
                  headData[i].valuehidden = fileInfo[0].newname + ';' + (headData[i].valuehidden && headData[i].valuehidden != null && headData[i].valuehidden != undefined && headData[i].valuehidden != 'undefined' ? headData[i].valuehidden : '')
                  headData[i].value = fileInfo[0].oldname + ';' + (headData[i].value && headData[i].value != null && headData[i].value != undefined && headData[i].value != 'undefined' ? headData[i].value : '')
                }
              }
              break
            }
          }
          Toast('上传成功')
        } else {
          Toast('上传失败')
        }
      }).catch(res => {
        //console.log(file)
      })
      // let headdata = this.jsondata.head[0].groupvalue
      //console.log(file)
      //console.log(detail)
    },
    delFileHead(file, detail) {
      if (this.ishead) {
        for (let headIdx = 0; headIdx < this.jsondata.head.length; headIdx++) {
          let headData = this.jsondata.head[headIdx].groupvalue
          for (let i = 0; i < headData.length; i++) {
            if (headData[i].sField === detail.name) {
              let fileVal = headData[i].valuehidden.split(';')
              let fileTitle = headData[i].value.split(';')
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] === file.file.name) {
                  fileVal[j] = ''
                  fileTitle[j] = ''
                }
              }
              let fileVal1 = ''
              let fileTitle1 = ''
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] !== '') {
                  fileVal1 += fileVal[j] + ';'
                  fileTitle1 += fileTitle[j] + ';'
                }
              }
              headData[i].valuehidden = fileVal1
              headData[i].value = fileTitle1
            }
          }
        }
      } else {
        for (let key in this.jsondata.bodydata) {
          let headData = this.jsondata.bodydata[key][this.index]
          for (let i = 0; i < headData.length; i++) {
            if (headData[i].sField === detail.name) {
              let fileVal = headData[i].valuehidden.split(';')
              let fileTitle = headData[i].value.split(';')
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] === file.file.name) {
                  fileVal[j] = ''
                  fileTitle[j] = ''
                }
              }
              let fileVal1 = ''
              let fileTitle1 = ''
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] !== '') {
                  fileVal1 += fileVal[j] + ';'
                  fileTitle1 += fileTitle[j] + ';'
                }
              }
              headData[i].valuehidden = fileVal1
              headData[i].value = fileTitle1
            }
          }
          break
        }
      }
      Toast('删除成功')
    }
  },
  watch: {
    'itemdata.valuelist': {
      handler(value) {
        console.log("newval", value)
      }
    }
  }
}
</script>

<style scoped lang="less">
.fileField {
  padding: 10px 5px;
  border-bottom: 1px solid #eee;
  background: #fff;
  // padding: 10px 16px;
  color: #646566;
  line-height: 16px;
  font-size: 16px;
  font-weight: 400;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
